package love.yuanmengrobot.qianyugarden.controller;

import love.yuanmengrobot.qianyugarden.entity.*;
import love.yuanmengrobot.qianyugarden.service.*;
import love.yuanmengrobot.qianyugarden.entity.BookEventAbook;
import love.yuanmengrobot.qianyugarden.entity.User;
import love.yuanmengrobot.qianyugarden.entity.Yuanwen;
import love.yuanmengrobot.qianyugarden.service.BookService;
import love.yuanmengrobot.qianyugarden.service.BrowseArticlesService;
import love.yuanmengrobot.qianyugarden.service.ThousandLanguageService;
import love.yuanmengrobot.qianyugarden.service.YuanwenService;
import love.yuanmengrobot.qianyugarden.service.impl.YuanwenServiceImpl;
import love.yuanmengrobot.qianyugarden.utils.RandomUtils;
import love.yuanmengrobot.qianyugarden.utils.ResultObj;
import love.yuanmengrobot.qianyugarden.utils.SystemConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 园文(Yuanwen)表控制层
 *
 * @author makejava
 * @since 2021-07-13 14:00:42
 */
@Controller
@RequestMapping("yuanwen")
public class YuanwenController {
    /**
     * 服务对象
     */
    @Autowired
    YuanwenService yuanwenService;

    @Autowired
    BrowseArticlesService browseArticlesService;

    @Autowired
    BookService bookService;
    @Autowired
    ThousandLanguageService thousandLanguageService;


    @Autowired
    FavoritesService favoritesService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @RequestMapping("selectOne")
    public Yuanwen selectOne(String id) {
        return this.yuanwenService.queryById(id);
    }

    @RequestMapping("/creation")
    public String viewCreation(HttpServletRequest request, ModelMap map) {
//        String path = request.getContextPath();
//        System.out.println("path"+path);
//        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
//        System.out.println(basePath);
//        map.put("css_creation", basePath + "css/creation.css");
//        map.put("css_nav","css/nav.css");//可用，备用
        return "creation/creation";
    }

    @PostMapping(value = "/creationmain")
    //从左侧菜单栏跳转到创作页面
    public ModelAndView viewCreatoinmain(HttpServletRequest request, String objectid) {
        System.out.println(objectid);
        ModelAndView modelAndView = new ModelAndView();
        Yuanwen yuanwen = new Yuanwen();
        yuanwen = yuanwenService.queryById(objectid);
        if (yuanwen != null) {
            modelAndView.addObject("titleval", yuanwen.getTitle());
            modelAndView.addObject("contentval", yuanwen.getContent());
            System.out.println(yuanwen.getTitle());
            System.out.println(yuanwen.getContent());
        }
        modelAndView.setViewName("creation/creationmain");
        return modelAndView;
    }

    @PostMapping(value = "/creationmain1")
    //左侧菜单栏跳转到草稿页面
    public ModelAndView viewCreatoinmain1(HttpServletRequest request, int numberpage) {
        int count = yuanwenService.queryCountByStatus("草稿", getUserId(request));
        List<Yuanwen> list1 = yuanwenService.queryAllByStatus("草稿", numberpage - 1, 15, getUserId(request));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("yuanwenlist", list1);
        int pagenumber = count / 15;
        int a = count % 15;
        if (a != 0) {
            pagenumber = pagenumber + 1;
        }
        request.setAttribute("pagenumber", pagenumber);
        modelAndView.setViewName("creation/draftbox");
        return modelAndView;
    }

    @PostMapping(value = "/creationdraftpage")
    //草稿箱页面内的页数跳转
    public ModelAndView viewdraftpage(int numberpage, HttpServletRequest request) {
        System.out.println(numberpage);
        List<Yuanwen> list1 = null;
        list1 = yuanwenService.queryAllByStatus("草稿", (numberpage - 1) * 15, 15, getUserId(request));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("yuanwenlist", list1);
        modelAndView.setViewName("creation/draftbox::copy");
        return modelAndView;
    }


    @PostMapping(value = "/creationmain2")
    //左侧菜单栏跳转到回收站页面
    public ModelAndView viewCreatoinmain2(HttpServletRequest request, int numberpage) {
        int count = yuanwenService.queryCountByStatus("废弃", getUserId(request));
        List<Yuanwen> list1 = yuanwenService.queryAllByStatus("废弃", (numberpage - 1)*15, 15, getUserId(request));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("yuanwenlist", list1);
        int pagenumber = count / 15;
        int a = count % 15;
        if (a != 0) {
            pagenumber = pagenumber + 1;
        }
        request.setAttribute("pagenumber", pagenumber);
        modelAndView.setViewName("creation/throw");
        return modelAndView;
    }

    @PostMapping(value = "/creationthrowpage")
    //回收站页面内的页数跳转
    public ModelAndView viewthrowpage(int numberpage, HttpServletRequest request) {
        System.out.println(numberpage);
        List<Yuanwen> list1 = null;
        list1 = yuanwenService.queryAllByStatus("废弃", (numberpage - 1) * 15, 15, getUserId(request));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("yuanwenlist", list1);
        modelAndView.setViewName("creation/throw::copy");
        return modelAndView;
    }



    @PostMapping(value = "/creationmain3")
    //左侧菜单栏跳转到已发布页面
    public ModelAndView viewCreatoinmain3(HttpServletRequest request, int numberpage) {
        int count = yuanwenService.queryCountByStatus("发布", getUserId(request));
        List<Yuanwen> list1 = yuanwenService.queryAllByStatus("发布", numberpage - 1, 15, getUserId(request));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("yuanwenlist", list1);
        int pagenumber = count / 15;
        int a = count % 15;
        if (a != 0) {
            pagenumber = pagenumber + 1;
        }
        request.setAttribute("pagenumber", pagenumber);
        modelAndView.setViewName("creation/commited");
        return modelAndView;
    }

    @PostMapping(value = "/creationcommitpage")
    //已发布里的页面跳转
    public ModelAndView viewcommitpage(int numberpage, HttpServletRequest request) {
        System.out.println(numberpage);
        List<Yuanwen> list1 = null;
        list1 = yuanwenService.queryAllByStatus("发布", (numberpage - 1) * 15, 15, getUserId(request));
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("yuanwenlist", list1);
        modelAndView.setViewName("creation/commited::copy");
        return modelAndView;
    }

    @PostMapping(value = "/creationmain4")
//左侧菜单栏跳转到草稿页面
    public ModelAndView viewCreatoinmain4() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("css_upBook", "css/upBook/upBook.css");
        modelAndView.addObject("js_upBook", "js/upBook/upBook.js");
        modelAndView.addObject("lanList", thousandLanguageService.queryAllByType("语言"));
        modelAndView.addObject("frameList", thousandLanguageService.queryAllByType("框架"));
        modelAndView.setViewName("upBook/upBook");
        return modelAndView;
    }

    @ResponseBody
    @PostMapping(value = "/deleteyw")
//删除回收站，草稿箱的内容
    public String deleteyw(String objectid) {
        System.out.println(objectid);
        Boolean flag = false;
        Boolean flag1 = true;
        Yuanwen yuanwen = yuanwenService.queryById(objectid);
        if (yuanwen.getStatus().equals("发布")) {
            flag1 = false;
            yuanwen.setStatus("废弃");
            Yuanwen yuanwen1 = yuanwenService.update(yuanwen);
            System.out.println(yuanwen1.getStatus());
            if (yuanwen1.getObjectid().equals(yuanwen.getObjectid()))
                flag = true;
        }
        if (flag1 == true) {
            yuanwenService.deleteById(objectid);
            flag = true;
        }
        if (flag == true) {
            String data = "删除成功";
            return data;
        } else {
            String data = "删除失败，请稍候再试!";
            return data;
        }
    }

    @PostMapping(value = "/creationmain5")
    //左侧菜单栏跳转到我的实例
    public ModelAndView viewCreatoinmain5(HttpServletRequest request, int numberpage) {
        System.out.println("进入postcreate5+");
        int count = bookService.queryAllBooksCount(getUserId(request));
        System.out.println(count);
        List<Book> list1 = bookService.queryAllbookByLimit(getUserId(request), (numberpage - 1) * 15, 15);
        System.out.println(list1.size());
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("booklist", list1);
        int pagenumber = count / 15;
        int a = count % 15;
        if (a != 0) {
            pagenumber = pagenumber + 1;
        }
        request.setAttribute("pagenumber", pagenumber);
        modelAndView.setViewName("creation/myBook");
        return modelAndView;
    }

    @PostMapping(value = "/viewBookPage")
    //我的实例页面内的页数跳转
    public ModelAndView viewmybookpage(HttpServletRequest request, int numberpage) {
        System.out.println(numberpage);
        List<Book> list1 = null;
        list1 = bookService.queryAllbookByLimit(getUserId(request), (numberpage - 1) * 15, 15);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("yuanwenlist", list1);
        modelAndView.setViewName("creation/commited::copy");
        return modelAndView;
    }

    @ResponseBody
    @PostMapping(value = "/writeyuanwen")
    //提交创作的园文
    public String writeYuanwen(@RequestBody Yuanwen yuanwen, HttpServletRequest request) {

        User user=(User) request.getSession().getAttribute("UserInfo");
        String objectid="";
        System.out.println(user);
        System.out.println(user.getNickname());
        objectid = RandomUtils.createIdOX("LS");
        yuanwen.setObjectid(objectid);
        yuanwen.setUserid(user.getObjectid());
        yuanwen.setUser(user);
        yuanwen.setCreatetime(RandomUtils.getTime());
        yuanwen.setUserid(getUserId(request));
        Yuanwen yuanwen1 = yuanwenService.insert(yuanwen);
        if (yuanwen1.getStatus().equals("发布")) {
            if (yuanwen1 != null)
                return "发布成功！";
            else
                return "发布失败，请检查网络或稍候重试！";
        } else {
            if (yuanwen1 != null)
                return "已保存到草稿箱！";
            else
                return "保存失败，请检查网络或稍候重试！";
        }
    }

    @ResponseBody
    @PostMapping(value = "/deletebook")
//删除回收站，草稿箱的内容
    public String deletebook(String objectid) {
        System.out.println(objectid);
        Boolean flag = false;
        flag=bookService.deleteById(objectid);
        if (flag == true) {
            String data = "删除成功";
            return data;
        } else {
            String data = "删除失败，请稍候再试!";
            return data;
        }
    }

    public String getUserId(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            User user = (User) session.getAttribute("UserInfo");
            if (user != null) {
                return user.getObjectid();
            }
        }
        return null;
    }


    @ResponseBody
    @RequestMapping(value = "/getViewBrowseAritcle")
    public ModelAndView getViewBrowseAritcle(String objectId, HttpSession session) {
        String userId="UC49juwunbkbnlx";
        if (session != null) {//
            User user=(User)session.getAttribute("UserInfo");
            if(user!=null){
                userId=user.getObjectid();
            }
        }


        Map<String, Object> map = browseArticlesService.loadBrowseArticles(objectId,userId);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("/browseArticles/browseArticles");
        modelAndView.addObject("browseArticlesUserInfo",map.get("browseArticlesUserInfo"));
        modelAndView.addObject("RecentYuanwens",map.get("RecentYuanwens"));
        modelAndView.addObject("browseAritclesInfo",map.get("browseAritclesInfo"));
        modelAndView.addObject("isLikeYuanWen", browseArticlesService.isLikeYuanWen(objectId, userId));
        modelAndView.addObject("isCollectYuanWen", browseArticlesService.isCollectYuanWen(objectId, userId));
        modelAndView.addObject("favorites", favoritesService.getMenu(userId));
        modelAndView.addObject("isFollow",map.get("isFollow"));
        return modelAndView;
    }


    @RequestMapping("noCollect")
    @ResponseBody
    public ResultObj noCollect(String objectId,HttpSession session){
        String userId="";
        if (session != null) {//
            User user=(User)session.getAttribute("UserInfo");
            if(user!=null){
                userId=user.getObjectid();
            }
        }

        if(favoritesService.noCollect(objectId,userId)){
            return new ResultObj(SystemConstant.OK,"修改成功");
        }else {
            return new ResultObj(SystemConstant.ERROR,"修改失败");
        }
    }


    @RequestMapping("collect")
    @ResponseBody
    public ResultObj collect(String objectId,String favorite,HttpSession session){
        String userId="";
        if (session != null) {//
            User user=(User)session.getAttribute("UserInfo");
            if(user!=null){
                userId=user.getObjectid();
            }
        }

        if(favoritesService.addFavorites(objectId,favorite,userId)){
            return new ResultObj(SystemConstant.OK,"修改成功");
        }else {
            return new ResultObj(SystemConstant.ERROR,"修改失败");
        }
    }




    @RequestMapping("insertFolder")
    @ResponseBody
    public Favorites insertFolder(String folderName,HttpSession session) {
        String userId="";
        if (session != null) {//
            User user=(User)session.getAttribute("UserInfo");
            if(user!=null){
                userId=user.getObjectid();
            }
        }

        System.out.println("新建收藏夹"+userId);

        Favorites favorites = new Favorites();
        favorites.setObjectid(RandomUtils.createIdOX("COOLIGHT"));
        favorites.setUserid(userId);
        favorites.setFavoritename(folderName);
        return favoritesService.insert(favorites);
    }

    @ResponseBody
    @RequestMapping(value = "/follow")
    public ResultObj follow(String targetId, HttpSession session){
        String userId = "";
        if (session != null) {//
            User user=(User)session.getAttribute("UserInfo");
            if(user!=null){
                userId=user.getObjectid();
            }
        }

        if(browseArticlesService.follow(userId,targetId)){
            return new ResultObj(SystemConstant.OK,"修改成功");
        }else {
            return new ResultObj(SystemConstant.ERROR,"修改失败");
        }

    }


    @ResponseBody
    @RequestMapping(value = "/like")
    public ResultObj like(String targetId, HttpSession session){
        String userId = "";
        if (session != null) {//
            User user=(User)session.getAttribute("UserInfo");
            if(user!=null){
                userId=user.getObjectid();
            }
        }
        if(browseArticlesService.like(userId,targetId)){
            return new ResultObj(SystemConstant.OK,"修改成功");
        }else {
            return new ResultObj(SystemConstant.ERROR,"修改失败");
        }

    }
}
